package com.study.webapp.word;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFStyles;

public class DocxTest {

	public static void main(String[] args) {
		readDocx2("D:\\wordlib\\选段.docx");
	}

	public static String readDocx2(String path) {
		String text = null;
		String ptext = "";
		try {
			// InputStream is = new FileInputStream(path);
			OPCPackage open = XWPFDocument.openPackage(path);
			XWPFDocument doc = new XWPFDocument(open);
			XWPFStyles style = doc.getStyles();

			Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
			XWPFParagraph para = null;
			while (iterator.hasNext()) {
				para = iterator.next();
				String pstyleId = para.getStyleID();

				ptext = para.getParagraphText();
				System.out.println("Paragraph>>>>" + ptext);
				// XWPFDocument document = para.getDocument();
				// CTDocument1 ctd = document.getDocument();
				// String ctdString = ctd.xmlText();
				// System.out.println(ctdString);
				// XWPFHyperlink[] xlink = document.getHyperlinks();
				// System.out.println(xlink[0]);
				// List<CTHyperlink> links = para.getCTP().getHyperlinkList();
				// for (CTHyperlink link : links) {
				// String a = link.getRArray(0).getTArray(0).getStringValue();
				// System.out.println(a);
				// }
				// if (pstyleId != null) {
				// XWPFStyle xstyle = style.getStyle(pstyleId);
				// String name = xstyle.getName();
				// System.out.println(name);
				// }
				text = para.getText();
				System.out.println("text>>>>" + text);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return text;
	}

	public static String readDocx(String path) {
		// 都是只能用String，不能用Stringbuffer，还不知道原因
		String text = null;
		try {
			InputStream is = new FileInputStream(path);
			XWPFDocument doc = new XWPFDocument(is);
			XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
			text = extractor.getText();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return text;
	}

}
